<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :action="config.action"
      :data="data.uploadKey"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="data.imgUrl" :src="data.imgUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import { reactive, watch, onMounted } from "@vue/composition-api";
import { QiniuToken } from "@/api/common";

export default {
  name: "index",
  props: {
    imgUrl: {
      type: String,
      default: ""
    },
    config: {
      type: Object,
      default: () => {
      }
    }
  },
  setup(props, { root, emit }) {
    const data = reactive({
      imgUrl: "",
      uploadKey: {
        token: "",
        key: ""
      }
    });

    // 获取七牛云token
    const getQiniuToken = () => {
      let requestData = {
        "accesskey": props.config.accesskey,
        "secretkey": props.config.secretkey,
        "buckety": props.config.buckety
      };
      QiniuToken(requestData).then(res => {
        data.uploadKey.token = res.data.data.token;
      }).catch(error => {
        console.log(error);
      });
    };

    const handleAvatarSuccess = (res) => {
      let img = `${root.$store.getters["common/qiniuUrl"]}${res.key}`;
      data.imgUrl = img;
      emit("update:imgUrl", img);
    };

    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        root.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        root.$message.error("上传头像图片大小不能超过 2MB!");
      }

      let suffix = file.name;
      data.uploadKey.key = encodeURI(`${suffix}`);

      return isJPG && isLt2M;
    };
    /**
     * watch监听
     */
    watch(() => props.imgUrl, (value) => {
      data.imgUrl = value;
    });
    /**
     * 生命周期
     */
    onMounted(() => {
      getQiniuToken();
    });

    return {
      data,
      handleAvatarSuccess,
      beforeAvatarUpload
    };
  }
};
</script>

<style scoped>

</style>
